package com.lonely.web.controller.common;

import cloud.tianai.captcha.application.ImageCaptchaApplication;
import cloud.tianai.captcha.application.vo.CaptchaResponse;
import cloud.tianai.captcha.application.vo.ImageCaptchaVO;
import cloud.tianai.captcha.common.response.ApiResponse;
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
import cn.hutool.core.convert.Convert;
import com.lonely.system.domain.dto.captcha.CaptchaTrackDto;
import com.lonely.system.domain.dto.captcha.GenerateCaptchaDto;
import com.lonely.system.enums.CaptchaType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 验证码请求处理器
 *
 * @author: fzzf
 */
@RestController
@RequestMapping("/captcha")
@Api(tags = "验证码")
@Slf4j
public class CaptchaController {

    @Autowired
    private ImageCaptchaApplication imageCaptchaApplication;

//    public CaptchaController(ImageCaptchaApplication imageCaptchaApplication) {
//        this.imageCaptchaApplication = imageCaptchaApplication;
//    }


    /**
     * 生成验证码
     *
     * @param generateCaptchaDto
     * @return
     */
    @PostMapping("/generate")
    @ApiOperation(value = "生成验证码")
    public CaptchaResponse<?> generate(@RequestBody GenerateCaptchaDto generateCaptchaDto) {
        String captchaType = CaptchaType.getCaptchaTypeByTypeCode(generateCaptchaDto.getType());
        // 根据验证码类型生成对应的验证码
        CaptchaResponse<ImageCaptchaVO> captchaResponse = imageCaptchaApplication.generateCaptcha(captchaType);
        return captchaResponse;
    }

    /**
     * 校验验证码
     *
     * @param captchaTrackDto
     * @return
     */
    @PostMapping("/check")
    @ApiOperation(value = "校验验证码")
    public ApiResponse<?> check(@RequestBody CaptchaTrackDto captchaTrackDto) {
        ImageCaptchaTrack imageCaptchaTrack = Convert.convert(ImageCaptchaTrack.class, captchaTrackDto.getData());
        return imageCaptchaApplication.matching(captchaTrackDto.getId(), imageCaptchaTrack);
    }

}
